<?php
// forgot_password.php
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/functions/security.php';
session_start();

// 初始化错误数组
$errors = [];
$step = $_GET['step'] ?? 1;

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        // 步骤1：验证用户名
        if ($step == 1) {
            $username = clean_input($_POST['username'] ?? '');

            if (empty($username)) {
                throw new Exception('用户名不能为空');
            }

            // 查询用户信息
            $stmt = $pdo->prepare("SELECT id, security_question, security_answer_hash FROM users WHERE username = ?");
            $stmt->execute([$username]);
            $user = $stmt->fetch();

            if (!$user) {
                throw new Exception('用户不存在');
            }

            // 存储到会话
            $_SESSION['reset_user'] = [
                'id' => $user['id'],
                'question' => $user['security_question']
            ];
            header('Location: forgot_password.php?step=2');
            exit;

        // 步骤2：验证安全问题答案
        } elseif ($step == 2) {
            if (!isset($_SESSION['reset_user'])) {
                throw new Exception('会话已过期，请重新开始');
            }

            $answer = mb_strtolower(clean_input($_POST['answer'] ?? ''));
            $user_id = $_SESSION['reset_user']['id'];

            if (empty($answer)) {
                throw new Exception('答案不能为空');
            }

            // 获取正确答案哈希
            $stmt = $pdo->prepare("SELECT security_answer_hash FROM users WHERE id = ?");
            $stmt->execute([$user_id]);
            $hash = $stmt->fetchColumn();

            if (!password_verify($answer, $hash)) {
                throw new Exception('答案不正确');
            }

            $_SESSION['reset_verified'] = true;
            header('Location: forgot_password.php?step=3');
            exit;

        // 步骤3：设置新密码
        } elseif ($step == 3) {
            if (!isset($_SESSION['reset_verified']) || !$_SESSION['reset_verified']) {
                throw new Exception('验证未通过');
            }

            $password = $_POST['password'] ?? '';
            $confirm = $_POST['confirm_password'] ?? '';
            $user_id = $_SESSION['reset_user']['id'];

            // 验证密码
            if (strlen($password) < 8) {
                throw new Exception('密码至少需要8个字符');
            }

            if ($password !== $confirm) {
                throw new Exception('两次输入的密码不一致');
            }

            // 更新密码
            $hash = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("UPDATE users SET password = ? WHERE id = ?");
            $stmt->execute([$hash, $user_id]);

            // 清除会话数据
            unset($_SESSION['reset_user'], $_SESSION['reset_verified']);
            
            $_SESSION['success'] = '密码重置成功，请重新登录';
            header('Location: login.php');
            exit;
        }

    } catch (Exception $e) {
        $errors[] = $e->getMessage();
    }
}

// 显示页面内容
include 'includes/header.php';
?>

<div class="container mt-5">
    <div class="row justify-content-center">
        <div class="col-md-6">
            <div class="card shadow">
                <div class="card-body">
                    <!-- 步骤指示器 -->
                    <ul class="nav nav-pills mb-4 justify-content-center">
                        <li class="nav-item">
                            <a class="nav-link <?= $step==1?'active':'' ?>">1. 验证身份</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link <?= $step==2?'active':'' ?>">2. 安全问题</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link <?= $step==3?'active':'' ?>">3. 设置新密码</a>
                        </li>
                    </ul>

                    <?php if (!empty($errors)): ?>
                        <div class="alert alert-danger">
                            <?php foreach ($errors as $error): ?>
                                <div><?= htmlspecialchars($error) ?></div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>

                    <?php if ($step == 1): ?>
                        <!-- 步骤1：输入用户名 -->
                        <form method="post">
                            <div class="mb-3">
                                <label class="form-label">请输入用户名</label>
                                <input type="text" 
                                       class="form-control" 
                                       name="username" 
                                       required
                                       value="<?= htmlspecialchars($_POST['username'] ?? '') ?>">
                            </div>
                            <button type="submit" class="btn btn-primary w-100">下一步</button>
                        </form>

                    <?php elseif ($step == 2): ?>
                        <!-- 步骤2：验证安全问题 -->
                        <?php if (isset($_SESSION['reset_user'])): ?>
                            <form method="post">
                                <div class="mb-3">
                                    <label class="form-label">安全问题</label>
                                    <input type="text" 
                                           class="form-control" 
                                           value="<?= htmlspecialchars($_SESSION['reset_user']['question']) ?>" 
                                           readonly>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">请输入答案</label>
                                    <input type="text" 
                                           class="form-control" 
                                           name="answer" 
                                           required>
                                </div>
                                <button type="submit" class="btn btn-primary w-100">验证答案</button>
                            </form>
                        <?php endif; ?>

                    <?php elseif ($step == 3): ?>
                        <!-- 步骤3：设置新密码 -->
                        <form method="post">
                            <div class="mb-3">
                                <label class="form-label">新密码</label>
                                <div class="input-group">
                                    <input type="password" 
                                        class="form-control password-strength" 
                                        name="password"
                                        id="forgotPassword"
                                        required
                                        minlength="8"
                                        data-bs-toggle="popover"
                                        data-bs-custom-class="password-popover custom-popover"
                                        data-bs-placement="auto"
                                        data-bs-trigger="focus"
                                        data-bs-html="true"
                                        data-bs-title="密码要求"
                                        data-bs-content="<ul class='list-unstyled mb-0'>
                                            <li id='popover-length-forgot' class='text-danger'><i class='bi bi-x-circle-fill'></i> 至少8个字符</li>
                                            <li id='popover-lowercase-forgot' class='text-danger'><i class='bi bi-x-circle-fill'></i> 包含小写字母</li>
                                            <li id='popover-uppercase-forgot' class='text-danger'><i class='bi bi-x-circle-fill'></i> 包含大写字母</li>
                                            <li id='popover-number-forgot' class='text-danger'><i class='bi bi-x-circle-fill'></i> 包含数字</li>
                                        </ul>">
                                    <button type="button" 
                                            class="btn btn-outline-secondary toggle-password">
                                        <i class="bi bi-eye"></i>
                                    </button>
                                </div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">确认密码</label>
                                <div class="input-group">
                                    <input type="password" 
                                        class="form-control" 
                                        name="confirm_password" 
                                        id="confirmPassword"
                                        required
                                        minlength="8">
                                    <button type="button" 
                                            class="btn btn-outline-secondary toggle-password">
                                        <i class="bi bi-eye"></i>
                                    </button>
                                </div>
                            </div>
                            <button type="submit" class="btn btn-success w-100">提交新密码</button>
                        </form>
                    <?php endif; ?>

                    <div class="mt-3 text-center">
                        <a href="login.php" class="text-decoration-none">
                            <i class="bi bi-arrow-left"></i> 返回登录
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    // 仅用于forgot_password.php的密码强度验证
    document.addEventListener('DOMContentLoaded', function() {
        const passwordInput = document.getElementById('forgotPassword');
        if (passwordInput) {
            const popover = new bootstrap.Popover(passwordInput, {
                container: 'body',
                customClass: 'password-popover custom-popover',
                sanitize: false
            });
            
            function updatePasswordRequirements(value) {
                const requirements = {
                    length: value.length >= 8,
                    lowercase: /[a-z]/.test(value),
                    uppercase: /[A-Z]/.test(value),
                    number: /\d/.test(value)
                };

                Object.keys(requirements).forEach(key => {
                    const element = document.getElementById('popover-'+key+'-forgot');
                    if (element) {
                        const isValid = requirements[key];
                        element.classList.toggle('text-success', isValid);
                        element.classList.toggle('text-danger', !isValid);
                        const icon = element.querySelector('i');
                        if (icon) {
                            icon.className = isValid ? 'bi bi-check-circle-fill' : 'bi bi-x-circle-fill';
                        }
                    }
                });
            }
            
            passwordInput.addEventListener('shown.bs.popover', function() {
                updatePasswordRequirements(this.value);
            });
            
            passwordInput.addEventListener('input', function(e) {
                updatePasswordRequirements(e.target.value);
            });
        }
    });
</script>
<?php include 'includes/footer.php'; ?>